
package com.probiz.estore.system.dao.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;

import com.probiz.estore.common.model.system.MailQueue;
import com.probiz.estore.common.util.DateUtil;
import com.probiz.estore.core.dao.impl.HibernateGenericDaoImpl;
import com.probiz.estore.core.model.BaseObject;
import com.probiz.estore.system.dao.MailQueueDao;

/**
 * Dao implementation for MailQueue.
 */
public class MailQueueDaoImpl extends HibernateGenericDaoImpl<MailQueue>
		implements MailQueueDao {

	@Override
	protected void initFilterHqlMap() {
		filterHqlMap.put(BaseObject.FilterHqlName.DEFAULT, "select s from MailQueue s order by mailQueueId desc");
	}
	
	public List<MailQueue> fetchEmailListToProcess(int numOfEmailsPerTime) {
		Query queryObject = getSession().createQuery(
				"from MailQueue mq where sendStatus=? and nextRetryTime<?".intern());
		queryObject.setFirstResult(0);
		queryObject.setMaxResults(numOfEmailsPerTime);
		queryObject.setFetchSize(numOfEmailsPerTime);
		queryObject.setParameter(0, MailQueue.STATUS_NOT_SEND);
		queryObject.setParameter(1, DateUtil.getNow());
		return queryObject.list();
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.system.dao.MailQueueDao#deleteExpiredEmails(int)
	 */
	public void deleteExpiredEmails(int daysToKeep) {
		Date date = DateUtil.getNumOfDaysBeforeNow(daysToKeep);
		
		Query queryObject = getSession().createQuery("delete MailQueue mq where updateTime<?".intern());
		queryObject.setParameter(0, date);
		
		queryObject.executeUpdate();
		
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.system.dao.MailQueueDao#resetIncorrectEmails()
	 */
	public void resetIncorrectEmails(){
		Date date = DateUtil.getNumOfDaysBeforeNow(1);
		
		Query queryObject = getSession().createQuery("update MailQueue set sendStatus = "+MailQueue.STATUS_NOT_SEND+" where sendStatus=? and updateTime<?");
		queryObject.setParameter(0, MailQueue.STATUS_CANCELLED);
		queryObject.setParameter(1, date);
		
		queryObject.executeUpdate();
	}

}
